import Vue from 'vue'
import App from './App'
import store from './store/index.js' // 引入模块
import Vuex from 'vuex'
import $mRouter from './router/router.js'
import $mRoutesConfig from './config/routes.config.js'
import $mUtils from './utils/utils.js'
import baseUrl from '@/utils/getIp.js'
import axios from 'axios'

import messages from '@/locale/index.js'
let i18nConfig = {
	locale: uni.getLocale(),
	messages
}
import VueI18n from 'vue-i18n' // v8.x

import uView from '@/uni_modules/uview-ui';
import search from "@/components/topSearch/index.vue";
import bottomBtn from "@/components/bottomBtn/index.vue";

//引用自定义全局组件
import zyIcon from '@/uni_modules/zy-icon/components/zy-icon/zy-icon.vue'
import zyCell from '@/uni_modules/zy-cell/components/zy-cell/zy-cell.vue'
import zyGroup from '@/uni_modules/zy-group/components/zy-group/zy-group.vue'
import zyTag from '@/uni_modules/zy-tag/components/zy-tag/zy-tag.vue'
import zyLoad from '@/uni_modules/zy-loading/components/zy-loading/zy-loading.vue'
import zySearch from '@/uni_modules/zy-function-search/components/zy-function-search/zy-function-search.vue'
import zySelect from '@/uni_modules/zy-select/components/zy-select/zy-select.vue'
import zyTable from '@/uni_modules/zy-table/components/zy-table/zy-table.vue'
import zyForm from '@/uni_modules/zy-form/components/zy-form-data/zy-form.vue'
import zyForms from '@/uni_modules/zy-form/components/zy-form/zy-form.vue'
import zyFormItem from '@/uni_modules/zy-form/components/zy-form/zy-form-item.vue'
import zyInput from '@/uni_modules/zy-input/components/zy-input/zy-input.vue'
import zyButtonGroup from '@/uni_modules/zy-button/components/zy-button/zy-button-group.vue'
import zyButton from '@/uni_modules/zy-button/components/zy-button/zy-button.vue'
import zyEmpty from '@/uni_modules/zy-empty/components/zy-empty/zy-empty.vue'
import zySegmented from "@/uni_modules/zy-segmented-control/components/zy-segmented-control/zy-segmented-control.vue"
import zyPopup from '@/uni_modules/zy-popup/components/zy-popup/zy-popup.vue'
import zyNumberBox from '@/uni_modules/zy-number-box/components/zy-number-box/zy-number-box.vue'
//使用组件
Vue.component('search', search);
Vue.component('bottomBtn', bottomBtn);
Vue.component('zy-icon', zyIcon);
Vue.component('zy-cell', zyCell);
Vue.component('zy-group', zyGroup);
Vue.component('zy-tag', zyTag);
Vue.component('zy-load', zyLoad);
Vue.component('zy-search', zySearch);
Vue.component('zy-select', zySelect);
Vue.component('zy-table', zyTable);
Vue.component('zy-form', zyForm);
Vue.component('zy-forms', zyForms);
Vue.component('zy-form-item', zyFormItem);
Vue.component('zy-input', zyInput);
Vue.component('zy-button', zyButton);
Vue.component('zy-button-group', zyButtonGroup);
Vue.component('zy-empty', zyEmpty);
Vue.component('zy-segmented', zySegmented);
Vue.component('zy-popup', zyPopup);
Vue.component('zy-number-box', zyNumberBox);

import filters from '@/common/filter' //导入过滤器文件
Object.keys(filters).forEach(key => { //通过Object.key方法取出过滤器中导出的每个方法并挂在vue.filter上
	Vue.filter(key, filters[key])
})

Vue.use(Vuex)
Vue.use(uView)
Vue.use(VueI18n)
Vue.config.productionTip = false
//全局组件
const i18n = new VueI18n(i18nConfig)
Vue.config.productionTip = false
App.mpType = 'app'
const bus = new Vue();
Vue.prototype.$Bus = bus;
Vue.prototype.$mRouter = $mRouter;
Vue.prototype.$mRoutesConfig = $mRoutesConfig;
Vue.prototype.$store = store; // 注册全局属性
Vue.prototype.$mUtils = $mUtils;
Vue.prototype.$baseUrl = baseUrl;


// // 实现再次返回退出应用时不退出应用而是在后台运行
// let main = plus.android.runtimeMainActivity();
// //为了防止快速点按返回键导致程序退出重写quit方法改为隐藏至后台  
// plus.runtime.quit = function() {
// 	main.moveTaskToBack(false);
// };

// //重写toast方法如果内容为 ‘再次返回退出应用’ 就隐藏应用，其他正常toast 
// plus.nativeUI.toast = (function(str) {
// 	if (str == '再次返回退出应用') {
// 		plus.runtime.quit();
// 	} else {
// 		uni.showToast({
// 			title: '再次返回退出应用',
// 			icon: 'none'
// 		})
// 	}
// });

axios.defaults.adapter = function (config) {
    return new Promise((resolve, reject) => {
        let ajaxTimes = 0;

        // 简化 settle 函数
        function settle(response) {
            if (response.statusCode >= 200 && response.statusCode < 300) {
                resolve({
                    data: response.data,
                    status: response.statusCode,
                    statusText: 'OK',
                    header: response.header,
                    config: config
                });
            } else {
                reject({
                    response: {
                        data: response.data,
                        status: response.statusCode,
                        statusText: 'Error',
                        header: response.header,
                        config: config
                    }
                });
            }
        }

        ajaxTimes++;

        let loadingTitle = "加载中";
        if (config.url === '/main/login' || config.url === '/main/current') {
            loadingTitle = "正在登录中...";
        } else if (config.url === '/main/logout') {
            loadingTitle = "正在退出中...";
        }
        uni.showLoading({ title: loadingTitle, mask: true });

        // 手动实现 buildURL
        function buildURL(url, params) {
            if (!params) return url;
            const parts = [];
            for (const key in params) {
                if (params[key] !== null && params[key] !== undefined) {
                    parts.push(
                        encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
                    );
                }
            }
            const serializedParams = parts.join('&');
            return url + (url.includes('?') ? '&' : '?') + serializedParams;
        }

        const fullUrl = config.baseURL + buildURL(config.url, config.params);

        uni.request({
            method: config.method?.toUpperCase() || 'GET',
            url: fullUrl,
            header: config.headers.toJSON(), 
            data: config.data,
            dataType: config.dataType || 'json',
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: (response) => {
                settle(response);
                ajaxTimes--;
                if (ajaxTimes === 0) {
                    uni.hideLoading();
                }
            }
        });
    });
};

const app = new Vue({
	store,
	i18n,
	...App,
})
app.$mount()